package v1

import (
        "wskyygyso/api/app/models/book"
        "wskyygyso/api/app/models"
       "wskyygyso/api/app/requests"
       "wskyygyso/api/pkg/response"
       "github.com/gin-gonic/gin"
)

type BooksController struct {
   models.BaseModel
}

func (ctrl *BooksController) Index(c *gin.Context) {
    Books := book.All()
    response.Data(c, Books)
}

func (ctrl *BooksController) Show(c *gin.Context) {
    bookModel := book.Get(c.Param("id"))
    if bookModel.ID == 0 {
        response.Abort404(c)
        return
    }
    response.Data(c, bookModel)
}

func (ctrl *BooksController) Store(c *gin.Context) {

    request := requests.BookRequest{}
    if ok := requests.Validate(c, &request, requests.BookSave); !ok {
        return
    }

    bookModel := book.Book{
      //  FieldName:      request.FieldName,
    }
    bookModel.Create()
    if bookModel.ID > 0 {
        response.Created(c, bookModel)
    } else {
        response.Abort500(c, "创建失败，请稍后尝试~")
    }
}

func (ctrl *BooksController) Update(c *gin.Context) {

    bookModel := book.Get(c.Param("id"))
    if bookModel.ID == 0 {
        response.Abort404(c)
        return
    }

  //  if ok := policies.CanModifyBook(c, bookModel); !ok {
  //      response.Abort403(c)
  //      return
  //  }

    request := requests.BookRequest{}
    bindOk := requests.Validate(c, &request, requests.BookSave)
    if !bindOk {
        return
    }


    //bookModel.FieldName = request.FieldName
    rowsAffected := bookModel.Save()
    if rowsAffected > 0 {
        response.Data(c, bookModel)
    } else {
        response.Abort500(c, "更新失败，请稍后尝试~")
    }
}

func (ctrl *BooksController) Delete(c *gin.Context) {

    bookModel := book.Get(c.Param("id"))
    if bookModel.ID == 0 {
        response.Abort404(c)
        return
    }

   // if ok := policies.CanModifyBook(c, bookModel); !ok {
   //     response.Abort403(c)
   //     return
   // }

    rowsAffected := bookModel.Delete()
    if rowsAffected > 0 {
        response.SUCCESS(c)
        return
    }

    response.Abort500(c, "删除失败，请稍后尝试~")
}